package cn.xyy.jdbc.sql;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.xyy.common.annotation.jdbc.Table;
import cn.xyy.common.exception.JdbcException;
import cn.xyy.common.utils.StringUtils;

/**
 * sql 工具类
 * 
 * @author xyy
 *
 */
public class SqlUtils {

	public static <T> void validateTargetClass(T entity) {
		if (entity == null) {
			throw new JdbcException("SqlGenerator entity cannot be null");
		}
		Class<?> classz = entity.getClass();
		Table tableAnnotation = (Table) classz.getAnnotation(Table.class);
		if (tableAnnotation == null) {
			throw new JdbcException("SqlGenerator " + classz + "no @Table defined");
		}
		String table = tableAnnotation.value();
		if (StringUtils.isBlank(table)) {
			throw new JdbcException("SqlGenerator " + classz + "@Table value cannot be null");
		}
		Field[] fields = getFields(classz);
		if (fields == null || fields.length < 0) {
			throw new JdbcException("SqlGenerator " + classz + " no field defined");
		}
	}

	public static boolean typeIsNotNullValue(Class<?> type, Object filedValue) {
		// String
		if (type == java.lang.String.class) {
			if (filedValue == null || filedValue == "") {
				return false;
			}
			// Number
		} else if (type == java.lang.Integer.class || type == java.lang.Double.class || type == java.lang.Float.class
				|| type == java.lang.Long.class || type == java.lang.Short.class
				|| type == java.math.BigDecimal.class) {
			if (null == filedValue) {
				return false;
			}
			// Date
		} else if (type == java.util.Date.class || type == java.sql.Timestamp.class || type == java.sql.Date.class) {
			if (null == filedValue) {
				return false;
			}
			// Boolean
		} else if (type == java.lang.Boolean.class) {
			if (null == filedValue) {
				return false;
			}
		} else if (type == java.lang.Byte.class) {
			if (null == filedValue) {
				return false;
			}
		}
		return true;
	}

	public static <T> Field[] getFields(Class<T> targetClazz) {
		List<Field> list = new ArrayList<Field>();
		for (Field field : targetClazz.getDeclaredFields()) {
			list.add(field);
		}
		getSuperFields(list, targetClazz.getSuperclass());
		return list.toArray(new Field[list.size()]);

	}

	public static void getSuperFields(List<Field> list, Class<?> targetClazz) {
		for (Field field : targetClazz.getDeclaredFields()) {
			list.add(field);
		}
		if (targetClazz.getSuperclass() != null) {
			if (!"java.lang.Object".equals(targetClazz.getSuperclass().getName())
					&& targetClazz.getSuperclass() != null) {
				getSuperFields(list, targetClazz.getSuperclass());
			}
		}
	}

}
